import router from './router'
import store from './store'
// eslint-disable-next-line no-unused-vars
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// eslint-disable-next-line no-unused-vars
import { getToken } from '@/utils/auth' // get token from cookie
// eslint-disable-next-line no-unused-vars
import getPageTitle from '@/utils/get-page-title'
import { asyncRoutes } from './router'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // 白名单

router.beforeEach(async(to, from, next) => {
  NProgress.start() // 开启进度条
  const Token = store.getters.token
  // debugger
  // console.log(Token)
  if (Token) {
    if (to.path === '/login') {
      next('/') // 路由后置守卫对于next('')，里面有路径的情况，不会执行，所以要手动关闭进度条
      NProgress.done()
    } else {
      if (!store.getters.userId) { // 判断是否获取过资料
        const res = await store.dispatch('user/getUserInfo')
        const filterRouter = asyncRoutes.filter(ele => { // 筛选路由
          return res.data.data.roles.menus.includes(ele.name)
        })
        store.commit('user/storeRouter', filterRouter) // 存储路由到vuex
        // 添加筛选后的动态路由到路由表,由于404页面只能放在所有路由的后面，所以要加在这里
        router.addRoutes([...filterRouter, { path: '*', redirect: '/404', hidden: true }])
        // router.options.routes = constantRoutes.concat([...filterRouter, { path: '*', redirect: '/404', hidden: true }])
        // router添加动态路由之后 需要转发一下
        next(to.path) // 目的是让路由拥有信息 router的已知缺陷
      } else {
        next() // 放行
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 关闭进度条
  NProgress.done()
})
